import java.io.*;
import java.util.*;
import java.security.MessageDigest;

/**
 * Authentication.java
 * 
 * This class is used for ensuring you have a valid username and password.  The passwords are
 * encrypted using a SHA1 hash, which is more secure than the commonly used MD5 
 * 
 */

public class Authentication {
	public static String encrypt(String s){
		return hash(s);
	}
	
	//Method for adding a new user.  Mainly used for populating the list of users for testing
	//purposes
	public static void addUser(String username, String password){
		try { 
			BufferedWriter out = new BufferedWriter(new FileWriter("users.txt", true)); 
			out.write(username);
			out.newLine();
			out.write(encrypt(password));
			out.newLine();
			out.close();
		} 
		catch (IOException e) {
			System.out.println("FILENOTFOUND!!!");
		} 
	}
	
	public static boolean verify(String username, String password){
		try{
			Scanner scan=new Scanner(new File("users.txt"));
			String currl;
			boolean founduser=false;
			while (scan.hasNextLine()) {
	            currl=scan.nextLine();
	            if(currl.equals(username)){
	                founduser=true;
	            }
	            currl=scan.nextLine();
	            if(founduser && encrypt(password).equals(currl))
	                return true;
	            founduser=false;
	        }
		}
		catch(FileNotFoundException e){
			System.out.println("FILE NOT FOUND");
		}
		return false;
	}
	
	//gets the hash of any string in SHA1 encryption
	private static String hash(String str){
		try{
			MessageDigest sha1 = MessageDigest.getInstance("SHA1");
			byte[] digest = sha1.digest((str).getBytes());
			return byteToHex(digest);
		}
		catch(Exception e){
			System.out.println(e);
			return "";
		}
		
	}
	
	//converts bytes to a hex string
	private static String byteToHex(byte[] bites){
		Formatter formatter=new Formatter();
		for (byte b : bites) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
	}
}